package me.leon.keeplive

import android.annotation.SuppressLint
import android.app.KeyguardManager
import android.content.ComponentName
import android.content.Context
import android.content.Context.KEYGUARD_SERVICE
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import androidx.core.app.NotificationManagerCompat

/**
 * @author : Leon Shih
 * @time : 2018/10/16 0016 11:28
 * @e-mail : deadogone@gmail.com :
 * @desc : 系统声音 和 锁屏工具类
 */
object OSHelper {

    private const val TAG = "OSHelper"
    var debug = true
    private var ctx: Context? = null
    fun init(ctx: Context) {
        OSHelper.ctx = ctx
    }

    /**
     * Return whether the app is installed.
     *
     * @param pkgName The name of the package.
     * @return `true`: yes<br></br>`false`: no
     */
    fun isAppInstalled(pkgName: String): Boolean {
        val packageManager = ctx?.packageManager
        return try {
            packageManager?.getApplicationInfo(pkgName, 0) != null
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * Return the application's name.
     *
     * @param packageName The name of the package.
     * @return the application's name
     */
    fun getAppName(packageName: String? = ctx?.packageName): String? {
        return if (packageName.isNullOrEmpty()) ""
        else
            try {
                val pm = ctx?.packageManager
                val pi = pm?.getPackageInfo(packageName, 0)
                pi?.applicationInfo?.loadLabel(pm)?.toString()
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                ""
            }
    }

    /** 唤醒手机屏幕并解锁 */
    @SuppressLint("InvalidWakeLockTag")
    fun wakeUpAndUnlock() {
        // 获取电源管理器对象
        val pm: PowerManager? = ctx?.getSystemService(Context.POWER_SERVICE) as PowerManager
        pm?.run {
            val screenOn = isScreenOn
            if (!screenOn) {
                // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
                val wl =
                    newWakeLock(
                        PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
                        "bright"
                    )
                wl.acquire(10000) // 点亮屏幕
                wl.release() // 释放
            }
            // 屏幕解锁
            val keyguardManager = ctx?.getSystemService(KEYGUARD_SERVICE) as KeyguardManager

            val keyguardLock = keyguardManager.newKeyguardLock("unLock")
            keyguardLock.disableKeyguard() // 解锁
        }
    }

    /** 自启动设置 */
    fun goAutoStar() {
        try {
            getAutoStartIntent()
                .also { Log.d(TAG, it.toString()) }
                ?.apply {
                    addFlags(FLAG_ACTIVITY_NEW_TASK)
                    if (debug) Log.d(TAG, component.toString())
                }
                ?.run {
                    if (ctx?.packageManager?.resolveActivity(this, 0) == null) {
                        action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                        data = Uri.fromParts("package", ctx?.packageName, null)
                    }
                    ctx?.startActivity(this)
                }
        } catch (e: Exception) {
            if (debug) Log.d(TAG, Log.getStackTraceString(e))
            ctx?.startActivity(
                Intent(Settings.ACTION_SETTINGS).apply { addFlags(FLAG_ACTIVITY_NEW_TASK) }
            )
        }
    }

    private fun getAutoStartIntent() =
        when (Build.MANUFACTURER) {
            "Xiaomi" ->
                Intent().apply {
                    component =
                        ComponentName(
                            "com.miui.securitycenter",
                            "com.miui.permcenter.autostart.AutoStartManagementActivity"
                        )
                }
            "HUAWEI" ->
                Intent().apply {
                    component =
                        ComponentName.unflattenFromString(
                            "com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity"
                        )
                    //
                    // ComponentName.unflattenFromString("com.huawei.systemmanager/.appcontrol.activity.StartupAppControlActivity")
                }
            "Honor" ->
                Intent().apply {
                    component =
                        ComponentName.unflattenFromString(
                            "com.huawei.systemmanager/.optimize.process.ProtectActivity"
                        )
                }
            "OPPO" -> getOppoAutoStartIntent()
            "vivo" ->

                // 设置了权限 无法直接跳转
                //                Intent().apply {
                //                component =  ComponentName(
                //                    "com.vivo.permissionmanager",
                //                    "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"
                //                )
                //            }

                ctx?.packageManager?.getLaunchIntentForPackage("com.iqoo.secure")
            "Letv" ->
                Intent().apply {
                    component =
                        ComponentName(
                            "com.letv.android.letvsafe",
                            "com.letv.android.letvsafe.AutobootManageActivity"
                        )
                }
            "Meizu" ->
                Intent().apply {
                    component =
                        ComponentName.unflattenFromString(
                            "com.meizu.safe/.permission.SmartBGActivity"
                        )
                } // 360手机 原酷派
            "ulong" ->
                Intent().apply {
                    component =
                        ComponentName(
                            "com.yulong.android.coolsafe",
                            ".ui.activity.autorun.AutoRunListActivity"
                        )
                }
            "samsung" ->
                Intent().apply {
                    component =
                        ComponentName(
                            "com.samsung.android.sm_cn",
                            "com.samsung.android.sm.ui.ram.AutoRunActivity"
                        )
                }
            "smartisan" ->
                ctx?.packageManager?.getLaunchIntentForPackage("com.smartisanos.security")
            else -> null
        }.also { if (debug) Log.d(TAG, Build.MANUFACTURER) }

    fun hasBatteryOptimization() =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            (ctx?.getSystemService(Context.POWER_SERVICE) as PowerManager?)
                ?.isIgnoringBatteryOptimizations(ctx?.packageName)
                ?: false
        else true

    /** Oppo 垃圾 */
    private val cmpList =
        arrayOf(
            "com.coloros.safecenter/.permission.startup.FakeActivity",
            "com.coloros.safecenter/.permission.startupapp.StartupAppListActivity",
            "com.coloros.safecenter/.permission.startupmanager.StartupAppListActivity",
            "com.coloros.safecenter/.permission.startupapp.StartupAppListActivity",
            "com.coloros.safe/.permission.startup.StartupAppListActivity",
            "com.coloros.safe/.permission.startupmanager.StartupAppListActivity",
            "com.coloros.safecenter/.permission.startupapp.startupmanage",
            "com.coloros.safecenter/.permission.startsettings",
            "com.coloros.safecenter/com.coloros.privacypermissionsentry.PermissionTopActivity.Startupmanager",
            "com.coloros.safecenter/.FakeActivity",
            "com.coloros.phonemanager/.FakeActivity"
        )

    private fun getOppoAutoStartIntent(): Intent? {

        for (cmp in cmpList) {

            Intent()
                .apply {
                    component = ComponentName.unflattenFromString(cmp)
                    addFlags(FLAG_ACTIVITY_NEW_TASK)
                }
                .also {
                    if (ctx?.packageManager?.resolveActivity(it, 0) != null) {
                        println(cmp)
                        return it
                    }
                }
        }
        return null
    }

    fun goAppDetail() {
        ctx?.startActivity(
            Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                flags = FLAG_ACTIVITY_NEW_TASK
                data = Uri.parse("package:${ctx?.packageName}")
            }
        )
    }

    /**
     * 电池优化
     *
     * 需要清单声明权限 android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
     */
    fun goBatteryOptimization() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val intent =
                Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
                    flags = FLAG_ACTIVITY_NEW_TASK
                    data = Uri.parse("package:" + ctx?.packageName)
                }
            ctx?.packageManager?.resolveActivity(intent, 0)?.run { ctx?.startActivity(intent) }
        }
    }

    fun goLimitless(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getLimitlessIntent()?.let {
                ctx?.packageManager?.resolveActivity(it, 0)?.run {
                    return try {
                        ctx?.startActivity(it)
                        true
                    } catch (ignored: Exception) {
                        false
                    }
                }
            }
                ?: return false
        } else return false
    }

    /** 电池设置 后台无限制 */
    private fun getLimitlessIntent() =
        when (Build.MANUFACTURER) {
            "Xiaomi" ->
                Intent().apply {
                    component =
                        ComponentName(
                            "com.miui.powerkeeper",
                            "com.miui.powerkeeper.ui.HiddenAppsConfigActivity"
                        )
                    flags = FLAG_ACTIVITY_NEW_TASK
                    putExtra("package_name", ctx!!.packageName)

                    putExtra("package_label", getAppName())
                }
            "Honor", "HUAWEI" ->
                Intent().apply {
                    component =
                        ComponentName(
                            "com.huawei.systemmanager",
                            "com.huawei.systemmanager.power.ui.PowerSettingActivity"
                        )
                    flags = FLAG_ACTIVITY_NEW_TASK
                }
            "vivo" -> ctx?.packageManager?.getLaunchIntentForPackage("com.iqoo.secure")
            else ->
                Intent(Intent.ACTION_POWER_USAGE_SUMMARY).apply { flags = FLAG_ACTIVITY_NEW_TASK }
        }.also { if (debug) Log.d(TAG, Build.MANUFACTURER) }

    /** 通知是否开启 */
    fun notificationEnable(ctx: Context) =
        NotificationManagerCompat.from(ctx.applicationContext).areNotificationsEnabled()

    /** 跳转通知设置页面 */
    fun goNotificationSettings(ctx: Context) {
        if (notificationEnable(ctx)) {
            if (debug) Log.d(TAG, "notification enabled")
            //            return
        }
        val intent = Intent()
        when (Build.VERSION.SDK_INT) {
            in 14..20 -> {
                // nop
            }
            in 21..25 -> {
                with(intent) {
                    action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                    intent.putExtra("app_package", ctx.packageName)
                    intent.putExtra("app_uid", ctx.applicationInfo.uid)
                }
            }
            else -> {
                with(intent) {
                    action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                    intent.putExtra(Settings.EXTRA_APP_PACKAGE, ctx.packageName)
                    intent.putExtra(Settings.EXTRA_CHANNEL_ID, ctx.applicationInfo.uid.toString())
                }
            }
        }

        ctx.packageManager?.resolveActivity(intent, 0)?.run {
            if (debug) Log.d(TAG, "notification 1")
            ctx.startActivity(intent)
            return
        }

        val i2 =
            Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                putExtra("package", ctx.packageName)
            }

        ctx.packageManager?.resolveActivity(i2, 0)?.run {
            if (debug) Log.d(TAG, "notification 2")
            ctx.startActivity(i2)
            return
        }
    }

    /** 悬浮窗权限 */
    fun goFloatWindows() {
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                val intent =
                    Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply {
                        flags = FLAG_ACTIVITY_NEW_TASK
                        data = Uri.parse("package:" + ctx?.packageName)
                    }
                ctx?.startActivity(intent)
            } catch (e: Exception) {
                Log.d("FloatWin", Log.getStackTraceString(e))
            }
        }
    }

    fun canDrawOverlays() = if (Build.VERSION.SDK_INT >= 23) Settings.canDrawOverlays(ctx) else true

    fun hasInstallUnknownPermission() =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            ctx?.packageManager!!.canRequestPackageInstalls()
        else true

    /**
     *
     * 安装未知应用权限 <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
     */
    fun goUnknownPermissionSettings() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ctx?.startActivity(
                Intent(
                        Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
                        Uri.parse("package:${ctx!!.packageName}")
                    )
                    .apply { flags = FLAG_ACTIVITY_NEW_TASK }
            )
        }
    }
}
